from common.libs.food.FoodService import ChangeFoodStockLog
from common.models.food import FoodStockChangeLog
from common.libs.Helper import getDictFilterFiled
from common.libs.Helper import getCurrentDate
from common.libs.Helper import selectFilterObj
from common.libs.UrlManager import UrlManager
from common.models.pay import PayOrderItem
from common.libs.Helper import ops_render
from common.models.member import Member
from common.models.food import FoodCat
from common.models.food import Food

from flask import Blueprint
from flask import request
from flask import jsonify
from flask import redirect
from application import app
from sqlalchemy import or_
import math

route_food = Blueprint('food_page', __name__)

@route_food.route('/index', methods=['GET', 'POST'])
def index():
    query = Food.query
    resp = request.values
    resp_data = {}

    # 混合搜索
    if 'mix_kw' in resp:
        rule = or_(
            Food.name.like('%{}%'.format(resp['mix_kw'])),
            Food.tags.like('%{}%'.format(resp['mix_kw']))
        )
        query = query.filter(rule)

    if 'cat_id' in resp and int(resp['cat_id']) > 0:
        query = query.filter(Food.cat_id == resp['cat_id'])

    # 搜索状态
    if 'status' in resp and int(resp['status']) > -1:
        query = query.filter(Food.status == resp['status'])

    # 指定当前页码
    page = resp.get('page', type=int)
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 创建分页对象
    pagination = query.filter().order_by(Food.id.desc()).paginate(page, page_size, False)
    # 获取美食分类的映射字典
    cat_mapping = getDictFilterFiled(FoodCat, FoodCat.id, 'id', [])
    resp_data['STATUS_LIST'] = app.config['STATUS_MAPPING']
    resp_data['pagination'] = pagination
    resp_data['search_val'] = resp
    resp_data['page_url'] = page_url
    resp_data['cat_mapping'] = cat_mapping
    resp_data['current'] = 'index'
    return ops_render('food/index.html', resp_data)

@route_food.route('/info')
def info():
    resp_data = {}
    back_url = UrlManager.buildUrl('/food/index')
    id = request.args.get('id')
    food_info = Food.query.get(id)
    if id and not food_info:
        return redirect(back_url)
    if food_info and food_info.status == 0:
        return redirect(back_url)

    # 销售记录
    pay_order_items = PayOrderItem.query.filter_by(food_id = id)\
        .order_by(PayOrderItem.id.desc()).limit(20).all()
    # 创建订单详情和会员映射关系
    member_ids = selectFilterObj(pay_order_items,'member_id')
    member_order_mapping = getDictFilterFiled(Member,Member.id,'id',member_ids)

    # 库存变更查询
    stock_list = FoodStockChangeLog.query.filter(
        FoodStockChangeLog.food_id == id
    ).order_by(FoodStockChangeLog.id.desc()).limit(20).all()

    resp_data['current'] = 'index'
    resp_data['food_info'] = food_info
    resp_data['stock_list'] = stock_list
    resp_data['pay_order_items'] = pay_order_items
    resp_data['member_order_mapping'] = member_order_mapping
    return ops_render('food/info.html', resp_data)

@route_food.route('/set', methods=['GET', 'POST'])
def set():
    if request.method == 'GET':
        resp_data = {}
        id = request.args.get('id')
        food = Food.query.get(id)
        if id and not food:
            return redirect('/food/index')
        if food and food.status == 0:
            return redirect('/food/index')
        # 获取美食分类的映射字典
        cat_mapping = getDictFilterFiled(FoodCat, FoodCat.id, 'id', [])
        # food_cat_list = FoodCat.query.filter(FoodCat.status == 1).all()
        # resp_data['food_cat_list'] = food_cat_list
        resp_data['cat_mapping'] = cat_mapping
        resp_data['food'] = food
        resp_data['current'] = 'index'
        return ops_render('food/set.html', resp_data)

    result = {'code': 200, 'msg': '操作成功!'}
    resp = request.values
    id = resp.get('id', type=int)
    cat_id = resp.get('cat_id', type=int)
    food_name = resp.get('food_name')
    price = resp.get('price', type=float)
    pic = resp.get('pic')
    summary = resp.get('summary')
    tags = resp.get('tags')
    stock = resp.get('stock', type=int)

    food_info = Food.query.filter_by(id=id).first()
    before_stock = 0
    if food_info:
        model_food = food_info
        before_stock = model_food.stock
        note = '修改库存'
    else:
        model_food = Food()
        model_food.status = 1
        note = '添加美食'
        model_food.created_time = getCurrentDate()

    model_food.cat_id = cat_id
    model_food.name = food_name
    model_food.price = price
    model_food.main_image = pic
    model_food.summary = summary
    model_food.stock = stock
    model_food.tags = tags
    model_food.updated_time = getCurrentDate()
    model_food.save()

    # 库存变更记录
    stock_change_number = int(stock) - int(before_stock)
    if stock_change_number:
        res = ChangeFoodStockLog(model_food.id,stock_change_number,note)
        if not res:
            result['code']=-1
            result['msg']='操作失败，请重试！'
            return jsonify(result)
    return jsonify(result)

@route_food.route('/food-ops', methods=['GET', 'POST'])
def food_ops():
    result = {'code': 200, 'msg': '操作成功!'}
    action = request.values.get('action')
    id = request.values.get('id')

    if not id:
        result['code'] = -1
        result['msg'] = '请指定操作的对象'
        return jsonify(result)

    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        result['code'] = -1
        result['msg'] = '指定操作的对象不存在！'
        return jsonify(result)

    if action == 'remove':
        food_info.status = 0

    if action == 'recover':
        food_info.status = 1
    food_info.update()
    return jsonify(result)

@route_food.route('/cat')
def cat():
    resp_data = {}
    resp = request.values
    query = FoodCat.query
    if 'status' in resp and int(resp['status']) > -1:
        query = query.filter_by(status=resp['status'])
    food_cat_list = query.filter().order_by(FoodCat.id.desc()).all()
    resp_data['food_cat_list'] = food_cat_list
    resp_data['STATUS_LIST'] = app.config['STATUS_MAPPING']
    resp_data['search_val'] = resp
    resp_data['current'] = 'cat'
    return ops_render('food/cat.html', resp_data)

@route_food.route('/cat-set', methods=['GET', 'POST'])
def cat_set():
    if request.method == 'GET':
        resp_data = {}
        id = request.args.get('id')
        food_cat = None
        if id:
            food_cat = FoodCat.query.get(id)
            if food_cat.status == 0:
                return redirect('/food/cat')
        resp_data['food_cat'] = food_cat
        resp_data['current'] = 'cat'
        return ops_render('food/cat_set.html', resp_data)

    result = {'code': 200, 'msg': '操作成功！'}
    resp = request.values
    name = resp.get('cat_name')
    weight = resp.get('weight', type=int)
    id = resp.get('id', default=0)

    if not name or len(name) < 1:
        result['code'] = -1
        result['msg'] = '请输入符合规则的分类名称'
        return jsonify(result)

    if math.floor(weight) < 0:
        result['code'] = -1
        result['msg'] = '权重不能为负数'
        return jsonify(result)

    food_cat_info = FoodCat.query.filter_by(id=id).first()
    if food_cat_info:
        model_food = food_cat_info
    else:
        model_food = FoodCat()
        model_food.created_time = getCurrentDate()

    model_food.name = name
    model_food.weight = weight
    model_food.updated_time = getCurrentDate()
    model_food.save()

    return jsonify(result)

@route_food.route('/cat-ops', methods=['POST'])
def cat_ops():
    result = {'code': 200, 'msg': '操作成功!'}
    action = request.values.get('action')
    id = request.values.get('id')

    if not id:
        result['code'] = -1
        result['msg'] = '请指定操作的对象'
        return jsonify(result)

    food_cat = FoodCat.query.filter_by(id=id).first()
    if not food_cat:
        result['code'] = -1
        result['msg'] = '指定操作的对象不存在！'
        return jsonify(result)

    if action == 'remove':
        food_cat.status = 0

    if action == 'recover':
        food_cat.status = 1
    food_cat.update()
    return jsonify(result)
